import { defineStore } from "pinia";
import { router } from "@/router";
import { routesMap } from "@/router/routesMap";
import type { RoutesMap } from "@/router/types";
import { addRoutes } from "@/router/routerHelper";
import { getUserMenu, loginCallback } from "@/api/manage/manage";
import type {
  GetUserMenuTree,
  UserMenuTreeItem,
  UserInfo,
} from "@/api/manage/model/manage";

export type MenuItem = Omit<UserMenuTreeItem, "children"> & {
  path: string;
  icon?: string;
  children?: MenuItem[] | [];
};
export type MenuList = MenuItem[];

interface PermissionState {
  menuList: MenuList;
  userInfo: UserInfo;
  hasGetPermission: boolean;
}

const menuIconMap = new Map([
  ["sc", "1.png"],
  ["pur", "2.png"],
  ["sys", "3.png"],
]);

export const usePermissionStore = defineStore("permissionStore", {
  state: (): PermissionState => ({
    menuList: [],
    userInfo: null,
    hasGetPermission: false,
  }),
  actions: {
    sendLoginCallback(cb: string) {
      loginCallback(cb).then((res) => {
        this.userInfo = res;
        localStorage.setItem("u", JSON.stringify(res));
        router.replace("/home");
      });
    },
    async getPermission() {
      const mode = import.meta.env.MODE;

      let userId =
        this.userInfo?.id || JSON.parse(localStorage.getItem("u") || "{}").id;
      if (mode === "development") {
        userId = 260000;
      }

      if (!userId) {
        router.replace("/login");
        return;
      }

      const res: GetUserMenuTree = await getUserMenu({
        userId,
      });

      let resMenuTree!: UserMenuTreeItem[];
      if (mode === "development") {
        resMenuTree = [
          {
            id: 91,
            text: "账号申请",
            hasChildren: true,
            children: [
              {
                attributes: { perms: "acc_application", url: "/accApp" },
                children: [],
                hasChildren: false,
                id: 92,
                state: { selected: true },
                text: "账号申请",
              },
              {
                attributes: { perms: "acc_logout", url: "/accLogout" },
                children: [],
                hasChildren: false,
                id: 93,
                state: { selected: true },
                text: "账号注销",
              },
              {
                attributes: { perms: "acc_record", url: "/accRecord" },
                children: [],
                hasChildren: false,
                id: 94,
                state: { selected: true },
                text: "申请记录",
              },
            ],
            attributes: {
              perms: "",
              url: "",
            },
            state: {
              selected: true,
            },
          },
          {
            id: 1,
            text: "系统管理",
            hasChildren: true,
            children: [
              {
                attributes: { perms: "sys_user", url: "/sys/user" },
                children: [],
                hasChildren: false,
                id: 2,
                state: { selected: true },
                text: "用户管理",
              },
              {
                attributes: { perms: "sys_role", url: "/sys/user" },
                children: [],
                hasChildren: false,
                id: 3,
                state: { selected: true },
                text: "角色管理",
              },
            ],
            attributes: {
              perms: "",
              url: "",
            },
            state: {
              selected: true,
            },
          },
        ];
      } else {
        resMenuTree = res.children;
      }

      // 获取菜单跳转路径
      const getMenuUrl = function (
        menuTree: UserMenuTreeItem[],
        routesMap: RoutesMap
      ): MenuItem[] {
        return menuTree.map((item) => {
          let children;
          if (item.children && item.children.length > 0) {
            children = getMenuUrl(item.children, routesMap);
          }
          const path = routesMap.get(item.attributes.perms)?.path || "";
          const icon = menuIconMap.get(item.attributes.perms) || "";
          return {
            ...item,
            path,
            icon,
            children,
          };
        });
      };
      this.menuList = getMenuUrl(resMenuTree, routesMap);
      // 根据权限更新路由对象
      addRoutes(this.menuList, routesMap, router);
      this.hasGetPermission = true;
    },
  },
  getters: {},
});
